package com.mhy.netsafe.utils.manager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

import java.util.Map;

/**
 * author    : mahongyin
 * e-mail    : mhy.work@qq.com
 * date      : 2019/6/12B 16:10
 * introduce : json解析管理类
 */

public class GsonManager {

    public Gson gson;
    private static GsonManager gsonManager;

    private GsonManager() {
        gson = new GsonBuilder().setVersion(1.0)
                .create();
    }

    public static GsonManager getInstance() {
        if (gsonManager == null) {
            synchronized (GsonManager.class) {
                if (gsonManager == null) {
                    gsonManager = new GsonManager();
                }
            }
        }
        return gsonManager;
    }

    /**
     * 用于将指定的Object对象序列化成相应的JSON数据
     *
     * @param object
     * @return
     */
    public String toJson(Object object) {
        return gson.toJson(object);
    }

    /**
     * 用于将JsonElement对象（可以是JsonObject、JsonArray等）转换成JSON数据
     *
     * @param jsonElement
     * @return
     */
    public String toJson(JsonElement jsonElement) {
        String str = gson.toJson(jsonElement);
        return str;
    }

    /**
     * @param jsonStr
     * @param classOfT
     * @param <T>
     * @return
     */
    public <T> T fromJson(String jsonStr, Class<T> classOfT) {
        return gson.fromJson(jsonStr, classOfT);
    }

    /**
     * 将Map转化为Json0
     * @param map
     * @param <T>
     * @return
     */
    public static <T> String mapToJson(Map<String, T> map) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(map);
        return jsonStr;
    }

}
